var app = getApp();
const qiniu = require("../../utils/qiniuUploader");

Page({
    /**
     * 页面的初始数据
     */
    data: {
        bs_name: '',    // 商家名称
        intro: '',      // 商家简介
        id_card: [],    // 身份证照
        address: '',    // 联系地址
        user_name: '',  // 联系人姓名
        qq_code: '',    // QQ 号
        tel: '',        // 固定电话
        phone: '',      // 手机号码
        code: '',       // 验证码
		rule: ['rule'],       // 规则选择

        files_num: 0,   // 当前图片ID

        time: 60,        // 获取短信间隔时间
        storeTime: 60,   // 存储获取短信间隔时间
        btnDisabled:false,// 是否禁用按钮

        qiniu_token:"",
        qiniu_link:"",          
    },
    // 失去焦点保存数据
    blurCallBack(e) {
        var val = e.detail.value; 
        var name = e.target.dataset.name;
        console.log(val,name)

        if ( name == 'bs_name'   ){ this.setData( { bs_name : val   } ); return } 
        if ( name == 'intro'     ){ this.setData( { intro : val     } ); return } 
        if ( name == 'site'      ){ this.setData( { address : val   } ); return } 
        if ( name == 'name'      ){ this.setData( { name : val      } ); return }
        if ( name == 'qq_code'   ){ this.setData( { qq_code : val   } ); return }
        if ( name == 'tel'       ){ this.setData( { tel : val       } ); return }
        if ( name == 'phone'     ){ this.setData( { phone : val     } ); return } 
        if ( name == 'code'      ){ this.setData( { code : val      } ); return } 
    },
    // 切换商家类型
    typeChange(e) {
        this.setData({
            type: parseInt(this.data.typeArray[e.detail.value].type),
            typeIndex: e.detail.value,
        })
    },
    // 上传图片
    uploadImg(e) {
        var self = this;
        var img_type = e.target.dataset.type;
        var id_card = this.data.id_card;
        var license = this.data.license;

        var qiniu_link = this.data.qiniu_link;
        var qiniu_token = this.data.qiniu_token;
        var uploadURL = "https://upload.qiniup.com";

        console.log(qiniu_link, qiniu_token)

        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                const tempFilePaths = res.tempFilePaths;
                for (var i = 0; i < tempFilePaths.length; i++) {
                    var file = tempFilePaths[i];

                    var uploader = qiniu.upload(file, (res) => {
                        var url = res.imageURL;
                        var id = res.hash;

                        id_card.push({
                            id: id,
                            url: url
                        })
                        self.setData({
                            id_card: id_card
                        })
                    }, (error) => {
                        console.log('error: ' + error);
                    }, {
                        uploadURL: uploadURL,
                        domain: qiniu_link,
                        uptoken: qiniu_token,
                    });
                }
            }
        })
    },
    // 删除图片
    deleteImg(e) {
        var self = this;
        var type = e.target.dataset.type
        var id = e.target.dataset.id;
        var id_card = this.data.id_card;
        var license = this.data.license;
        id_card.map((item, index) => {
            if (item.id == id) {
                id_card.splice(index, 1)
            }
        })
        this.setData({
            id_card: id_card
        })
    },
    // 选择入驻手册
    ruleSelect(e) {
        var rule = e.detail.value;
        this.setData({
            rule: rule
        })
    },
    // 获取用户地理位置授权 并 选择位置
    location() {
        var address = this.data.address;
        var self = this;

        wx.getSetting({
            success(res) {
                if (!res.authSetting['scope.userLocation']) {
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success() {
                            wx.chooseLocation({
                                success(res) {
                                    address = res.address + res.name;
                                    self.setData({
                                        address: address,
                                    })
                                }
                            })
                        },
                        fail() {
                            self.localtion.showModalBox()
                        },
                    })
                } else {
                    console.log("已授权")
                    wx.chooseLocation({
                        success(res) {
                            address = res.address + res.name;
                            self.setData({
                                address: address,
                            })
                        }
                    })
                }
            }
        })
    },
    // 获取短信验证码
    sendcode(){
        var time = this.data.storeTime;
        var timeEnd = new Date().getTime() + time * 1000;
        var self = this;
        var phone = this.data.phone;
        var reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|17[0-9]|18[0|1|2|3|4|5|6|7|8|9]|19[8|9])\d{8}$/;
        if (reg.test(phone)) { 
            wx.getStorage({
                key: 'user',
                success: function (res) {
                    wx.request({
                        url: app.url.requestUrl + '/message/sendcode',
                        method: 'POST',
                        data: {
                            openid: res.data.openid,
                            token: res.data.token,
                            mobile: phone
                        },
                        success: function (res) {
                            if(res.data.code == 1){
                                self.setData({ btnDisabled: true })
                                var timer = setInterval(function () {
                                    console.log(time)
                                    if (timeEnd - new Date().getTime() > 0) {
                                        self.setData({ time: --time })
                                    } else {
                                        clearInterval(timer)
                                        timer = null;
                                        self.setData({ 
                                            time: self.data.storeTime,
                                            btnDisabled: false
                                        })
                                    }
                                }, 1000)
                                wx.showToast({
                                    title: '发送成功',
                                })
                            }else{
                                wx.showToast({
                                    image:'../../img/warning.png',
                                    title: res.msg,
                                })
                            }
                        }
                    })
                    
                }
            })
        }else{
            wx.showToast({
                image: '../../img/warning.png',
                title: '手机号格式错误',
            })
            return;
        }
    },
    // 提交表单
    submit() {
        var data = {};
        var img1 = this.data.id_card || [];
		var rule = this.data.rule.toString();

        data.bs_name    =   this.data.bs_name;
        data.type       =   this.data.type;
        data.intro      =   this.data.intro;
        data.address    =   this.data.address;
        data.name       =   this.data.name;
        data.qq         =   this.data.qq_code;
        data.phone      =   this.data.phone;
        data.tel        =   this.data.tel;
        data.code       =   this.data.code;
        var id_card    =   [];

        img1.map((item, index) => {
            id_card.push(item.url);
        });

        data.id_card = id_card.join(",")

        if (!data.bs_name) { // 商家名称
            wx.showToast({
                image: '../../img/warning.png',
                title: '请输入商家名称',
            })
            return false;
        }
        if (!data.intro) { // 商家简介
            wx.showToast({
                image: '../../img/warning.png',
                title: '请输入商家简介',
            })
            return false;
        }
        if (!data.id_card) { // 身份证照
            wx.showToast({
                image: '../../img/warning.png',
                title: '请上传身份证照',
            })
            return false;
        }
        // if (data.type == 2 && !data.license.length) {   // 营业执照
        //     wx.showToast({
        //         image: '../../img/warning.png',
        //         title: '请上传营业执照',
        //     })
        //     return false;
        // }
        if (!data.address) { // 联系地址
            wx.showToast({
                image: '../../img/warning.png',
                title: '请选择联系地址',
            })
            return false;
        }
        if (!data.name) {  // 联系人姓名
            wx.showToast({
                image: '../../img/warning.png',
                title: '请输入联系人',
            })
            return false;
        }
        if (!data.phone) {  // 联系人手机号
            wx.showToast({
                image: '../../img/warning.png',
                title: '请输入手机号码',
            })
            return false;
        }
        if (!data.code) {   // 手机号验证码
            wx.showToast({
                image: '../../img/warning.png',
                title: '请输入验证码',
            })
            return false;
        }
		if (!rule) {   // 请勾选入驻协议
			wx.showToast({
				image: '../../img/warning.png',
				title: '请勾选入驻协议',
			})
			return false;
		}
        this.submitEntrust(data);
    },
    // 表单填入完成且无错误
    submitEntrust(data) {
        wx.getStorage({
            key: 'user',
            success: function(res) {
                data.openid = res.data.openid;
                data.token = res.data.token;
                wx.request({
                    url: app.url.requestUrl + '/user/apply_cattle',
                    method: 'POST',
                    data: data,
                    success: function(res) {
                        if (res.data.code == 1) {
                            wx.showToast({
                                title: '申请成功，待审核',
                            })
                            setTimeout(function () {
                                wx.redirectTo({
									url: '../trading-hn-apply-status/trading-hn-apply-status',
								})
                            }, 2000)
                            
                        } else {
                            wx.showToast({
                                image:'../../img/warning.png',
                                title: res.data.msg,
                            })
                        }
                    }
                })
            }
        })
    },
    // 获取七牛所需数据
    getQiniuInfo() {
        var self = this;
        var url = "/upload/token";

        wx.getStorage({
            key: 'user',
            success: function (res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token
                    },
                    success: function (res) {
                        var datas = res.data;
                        if (datas.code == 1) {
                            self.setData({
                                qiniu_token: datas.data.token,
                                qiniu_link: datas.data.url
                            })
                        }
                    }
                })
            }
        })
    },
    // 生命周期函数--监听页面加载
    onLoad: function(options) {
        this.localtion = this.selectComponent("#localtion");
        console.log(options.id)
        this.getQiniuInfo();
    },
    // 授权地理位置
    __accreditEvent(e) {
        console.log(e)
        this.localtion.hideModalBox()
    },
    onShow() {
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})